﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SMS
{
    class ShortMessageGenerator
    {

        static Dictionary<string, string> _replaceables;
        static List<string> _fields;
        static string Message { get; set; }

        private static Dictionary<string, string> LoadFields()
        {
            XElement Element = XElement.Load("Fields.xml");
            var x = Element.Descendants().ToList();

            Dictionary<string, string> dictionary =
                x.ToDictionary<XElement, string, string>(k => k.Attribute("key").Value, k => k.Attribute("fieldname").Value);

            return dictionary;
        }

        static ShortMessageGenerator()
        {
            _fields = new List<string>();
            _replaceables = LoadFields();
        }



        internal static string Generate(List<string> list)
        {
           
            //check
            if (Message==null)
            {
                throw new ArgumentNullException("Message","Message can't be null , SetMessage Should be called first");
            }
            if (_fields!=null && list.Count < _fields.Count)
            {
                throw new InvalidOperationException("List provided must be of same size with the fields of the message");
            }


            //


            string temp = String.Copy(Message);
            for (int i = 0; i < _fields.Count; i++)
            {
               temp=temp.Replace(_fields[i], list[i]);
            }
            return temp;
        }

        internal static void SetMessage(string message)
        {
            _fields = new List<string>();
            foreach (var item in _replaceables)
            {
                if (message.Contains(item.Key))
                {
                    _fields.Add(item.Key);
                }
            }

            Message = message;
        }
    }
}
